<?php

namespace app\webapi\controller;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class ApiRush extends ApiBaseController
{
    public $user_info = null;

    public function __construct()
    {
        $this->user_info = $this->checkToken();
        if (!preg_match('/^\d+$/', $this->user_info['id'])) {
            $this->result_error('用户id出错');
        }
    }

    /** 获取抢购场次【2】 */
    public function getRushSchedule()
    {
        $user_info = $this->user_info;
        $data = ApiRedis::updateGet(self::KEYS['RUSH_SCHEDULE'], function () {
            $sql_result = Db::name('rush_schedule')->field('*,state as schedule_state')
                ->order('starttime', 'asc');
            return $sql_result;
        });
        if (count($data) > 0) {
            $data = array_filter($data, function ($item) use ($user_info) {
                return $item['bucket_id'] == $user_info['bucket_id'];
            });
        }
        $gtime = 0;
        if ($user_info['id'] > 0) {
            $god = ApiRedis::getUserGodState($user_info['id']);
            if ($god && $god['godtime']['use']) {
                $gtime = (int)($god['godtime']['use']) * 1000;
            }
        }
        $lastData = [
            'list' => array_values($data),
            'time' => date('Y-m-d H:i:s', time()),
            'gtime' => $gtime,
        ];
        $this->result_ok('ok', $lastData);
    }

//    private function updateGet($key, $func)
//    {
//        $data = Cache::store('redis')->get($key);
//        if (empty($data)) {
//            $data = $func();
//            Cache::store('redis')->set($key, json_encode($data));
//        } else {
//            $data = json_decode($data, true);
//        }
//        return $data;
//    }

//    private function getUserGodState($uid)
//    {
//        $limit = Cache::store('redis')->get(self::KEYS['USER_LIMIT'] . $uid);
//        $limit_remain = Cache::store('redis')->ttl(self::KEYS['USER_LIMIT'] . $uid);
//        $blacklist = Cache::store('redis')->get(self::KEYS['USER_BLACKLIST'] . $uid);
//        $blacklist_remain = Cache::store('redis')->ttl(self::KEYS['USER_BLACKLIST'] . $uid);
//        $blackroom = Cache::store('redis')->get(self::KEYS['USER_BLACKROOM'] . $uid);
//        $blackroom_remain = Cache::store('redis')->ttl(self::KEYS['USER_BLACKROOM'] . $uid);
//        $godtime = Cache::store('redis')->get(self::KEYS['USER_GODTIME'] . $uid);
//        $godtime_remain = Cache::store('redis')->ttl(self::KEYS['USER_GODTIME'] . $uid);
//        $datalimit = [
//            'use' => !empty($limit) && $limit > 0 ? true : false,
//            'data' => $limit > 0 ? $limit : 0,
//            'timeout' => $limit_remain > 0 ? $limit_remain : 0
//        ];
//        $datablacklist = [
//            'use' => $blacklist ? true : false,
//            'data' => $blacklist ? json_decode($blacklist, true) : [],
//            'timeout' => $blacklist_remain > 0 ? $blacklist_remain : 0
//        ];
//        $datablackroom = [
//            'use' => $blackroom > 0 ? true : false,
//            'data' => $blackroom > 0 ? $blackroom : 0,
//            'timeout' => $blackroom_remain > 0 ? $blackroom_remain : 0
//        ];
//        $datagodtime = [
//            'use' => $godtime > 0 ? true : false,
//            'data' => $godtime > 0 ? $godtime : 0,
//            'timeout' => $godtime_remain > 0 ? $godtime_remain : 0
//        ];
//
//        $result = [
//            'limit' => $datalimit,
//            'blacklist' => $datablacklist,
//            'blackroom' => $datablackroom,
//            'godtime' => $datagodtime
//        ];
//
//        return $result;
//
//    }

    /** 获取用户提前抢购时间 */
    public function getUserGTime()
    {
        $user_info = $this->user_info;
        $sid = Request::param('sid');
        $gtime = 0;
        if ($user_info['id'] > 0) {
            // await rush.newUserPrivilege(user_info); // 废弃不用
            // 查看用户是否设置上帝之手
            $god = ApiRedis::getUserGodState($user_info['id']);
            if ($god && $god['godtime']['use']) {
                if ($sid && $sid > 0) {
//                    $success_count = Cache::store('redis')->get('special_success_' . $user_info['id'] . '_' . $sid . '_count');
                    $success_count = APiRedisServer::selected(2)->get('special_success_' . $user_info['id'] . '_' . $sid . '_count');
                    $success_count = (int)($success_count);
                    // 检查用户有没有秒杀数量限制，如果有是否已经满足
                    if ($success_count >= $god['limit']['data']) {
                        $gtime = 0;
                    } else {
                        $gtime = (int)($god['godtime']['data']) * 1000;
                    }
                } else {
                    $gtime = (int)($god['godtime']['data']) * 1000;
                }
            }
        }
        $lastData = [
            'gtime' => $gtime,
        ];
        $this->result_ok('ok', $lastData);
    }

    /** 获取抢购物品列表【2】 */
    public function getRushGoods()
    {
        $user_info = $this->user_info;
        $uid = $user_info['id'];
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        $sid = (int)Request::param('sid');
        if ($page_size < 1) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index * $page_size;
        if (!($sid > 0)) {
            $this->result_ok('ok', []);
        }
        // 获取黑名单商品id列表
        $bidArr = [];
//        $blacklist = Cache::store('redis')->get(self::KEYS['USER_BLACKLIST'] . $uid);
        $blacklist = APiRedisServer::selected(2)->get(self::KEYS['USER_BLACKLIST'] . $uid);
        if (!empty($blacklist)) {
            $blacklist = json_decode($blacklist, true);
            $bidArr = array_column($blacklist, 'id');
        }
        // 获取恶意用户抢购过的商品id列表
        $badArr = [];
//        $badlist = Cache::store('redis')->get(self::KEYS['USER_BADLIST'] . $uid);
        $badlist = APiRedisServer::selected(2)->get(self::KEYS['USER_BADLIST'] . $uid);
        if (!empty($badlist)) {
            $badArr = json_decode($badlist, true);
        }

        //获取用户自己发布的商品列表
//        $userGoodsIds = Cache::store('redis')->hGet(self::KEYS['USER_BELONG'] . $uid);
        $userGoodsIds = APiRedisServer::selected(2)->hGet(self::KEYS['USER_BELONG'], $uid);
        if (empty($userGoodsIds)) {
            $userGoodsIds = [];
        } else {
            $userGoodsIds = json_decode($userGoodsIds, true);
        }
        // 获取所有的抢购商品id
//        $allGoodsKeys = Cache::store('redis')->hKeys(self::KEYS['RUSH_GOODS'] . $sid);
        $allGoodsKeys = APiRedisServer::selected(0)->hKeys(self::KEYS['RUSH_GOODS'] . $sid);
        // 过滤用户自己的商品和黑名单的商品
        $allGoodsKeys = array_filter($allGoodsKeys, function ($item) use ($bidArr, $userGoodsIds) {
            $id = (int)$item;
//            return empty($bidArr[$id]) && empty($userGoodsIds[$id]);
            return !in_array($id, $bidArr) && !in_array($id, $userGoodsIds);
        });
        //new
        if (count($allGoodsKeys) < 1) {
            $this->result_ok('ok', ['total_count' => 0, 'list' => []]);
        }

//        if ($user_info['bucket_id'] > 0) {
//
//            $bucket_goods = Cache::store('redis')->get(self::KEYS['BUCKET_GOODS_LIST'] . $user_info['bucket_id']);
//            if (!empty($bucket_goods)) {
//                $bucket_goods = json_decode($bucket_goods, true);
//            } else {
//                $bucket_goods = array();
//            }
//            $filterKeys = [];
//            // 分仓发布的商品有可能不在同一场次，所以过滤下
//            foreach ($bucket_goods as $v) {
//                if (!empty($allGoodsKeys[$v])) {
//                    $filterKeys[] = $v;
//                }
//            }
//            $allGoodsKeys = $filterKeys;
//
//        } else {
//            /**  不是分仓用户只能看普通商品 */
//            $bkeys = Cache::store('redis')->keys(self::KEYS['BUCKET_GOODS_LIST'] . '*');
//            if (count($bkeys) > 0) {
//                $bucket_goods = [];
//                foreach ($bkeys as $bv) {
//                    $bitem_goods = Cache::store('redis')->get($bv);
//                    if (!empty($bitem_goods)) {
//                        $bitem_goods = json_decode($bitem_goods, true);
//                        if (count($bitem_goods) > 0) {
//                            $bucket_goods = array_merge($bucket_goods, $bitem_goods);
//                        }
//                    }
//                }
//                $filterKeys = [];
//                foreach ($allGoodsKeys as $v) {
//                    if (empty($bucket_goods[$v])) {
//                        $filterKeys[] = $v;
//                    }
//                }
//                $allGoodsKeys = $filterKeys;
//            }
//        }
//        if (count($allGoodsKeys) == 0) {
//            $this->result_ok('ok', ['total_count' => 0, 'list' => []]);
//        }
        // 获取所有商品并排序
//        $data = Cache::store('redis')->hmGet(self::KEYS['RUSH_GOODS'] . $sid, $allGoodsKeys);
        $data = APiRedisServer::selected(0)->hmGet(self::KEYS['RUSH_GOODS'] . $sid, $allGoodsKeys);
        $data_c = array();
        foreach ($data as &$dv) {
            $obj = json_decode($dv, true);
            // 设置恶意用户抢购过的商品已售罄
            if (!empty($badArr[$obj['id']])) {
                $obj['state'] = 2;
            }
            $data_c[] = $obj;
        }
        $lastGoods_order = [];
        $lastGoods_cp = [];
        foreach ($data_c as $l1) {
            if ($l1['state'] == 1) {
                $lastGoods_order[] = $l1;
            } else {
                $lastGoods_cp[] = $l1;
            }
        }
        $data_c = array_merge(array_values($lastGoods_order), array_values($lastGoods_cp));
        $lastGoods = [];
        for ($i = $limit; $i < count($data_c) && $i < $limit + $page_size; $i++) {
            // $lastGoods[] = json_decode($data[$i], true);
            $lastGoods[] = $data_c[$i];
        }
        if (count($lastGoods) == 0) {
            $this->result_ok('ok', ['total_count' => 0, 'list' => []]);
        } else {
            $this->result_ok('ok', ['total_count' => count($allGoodsKeys), 'list' => $lastGoods]);
        }
    }

    /** v抢购【2】*/
    public function shoot()
    {
        $user_info = $this->user_info;
        if (!($user_info['level1_recommender'] > 0) && !in_array(1, $user_info['roles'])) {
            $this->result_error('很遗憾,您没有抢到');
        }
        $gid = (int)Request::param('gid');
        $sid = (int)Request::param('sid');
        // $address_info = (int)Request::param('address_info');
        $address_info = Request::param('address_info');
        if (!($gid > 0) || !($sid > 0)) {
            $this->result_error('抢购失败!');
        }
        if (!($user_info['level1_recommender'] > 0) && !in_array(1, $user_info['roles'])) {
            $this->result_error('很遗憾,您没有抢到');
        }
        // 初始化时间
        $curTime = time();
        $expiresTime = strtotime(date("Y-m-d 00:00:00", strtotime("+1 day"))); // 过期时刻
        $timeout = floor(($expiresTime - $curTime)); // 计算Timeout: 当前晚上12点过期
        if ($user_info['bad'] == 1) {
//            $badlist = Cache::store('redis')->get(self::KEYS['USER_BADLIST'] . $user_info['id']);
            $badlist = APiRedisServer::selected(2)->get(self::KEYS['USER_BADLIST'] . $user_info['id']);
            if (!empty($badlist)) {
                $badlist = json_decode($badlist, true);
            } else {
                $badlist = [];
            }
            if (empty($badlist['id'])) {
                $badlist[] = $gid;
            }
            APiRedisServer::selected(2)->setex(
                self::KEYS['USER_BADLIST'] . $user_info['id'],
                $timeout,
                json_encode($badlist)
            );
            $this->result_error('很遗憾,您没有抢到');
        }
        $mode = (int)Request::param('mode');
//        var_dump($mode);die;
        if ($mode == 1) {
            $data = $this->shootNormal($user_info,
                $curTime,
                date('Y', time()),
                date('m', time()),
                date('d', time()),
                $timeout,
                $gid,
                $sid,
                $address_info);
        } elseif ($mode == 2) {
            $god = ApiRedis::getUserGodState($user_info['id']);
            $data = $this->shootSpecial($user_info,
                $curTime,
                date('Y', time()),
                date('m', time()),
                date('d', time()),
                $timeout,
                $gid,
                $sid,
                $address_info, $god);
        }

    }

    /** 特权抢购 */
    public function shootSpecial($user_info, $curTime, $y, $M, $d, $timeout, $gid, $sid, $address_info, $god)
    {
        if (!($god['limit']['use'] && $god['godtime']['use'])) {
            $this->result_error("优先抢购数量已用完，请等待正式抢购!");
        }
        // 检查抢购的商品是不是用户不可见的商品
        if ($god['blacklist']['use']) {
            $findGoods = '';
            foreach ($god['blacklist']['data'] as $v) {
                if ($v['id'] == $gid) {
                    $findGoods = $v;
                    break;
                }
            }
            // 如果是，抢购失败（此情况发生证明数据出现了BUG，或者用户非法手段抢购）
            if ($findGoods) {
                $this->result_error("抢购失败!");
            }
        }
//        $success_count = Cache::store('redis')->get('special_success_' . $user_info['id'] . '_' . $sid . '_count');
        $success_count = APiRedisServer::selected(2)->get('special_success_' . $user_info['id'] . '_' . $sid . '_count');
        $success_count = (int)$success_count;
        // 检查用户有没有秒杀数量限制，如果有是否已经满足
        if ($success_count >= $god['limit']['data']) {
            $this->result_error('优先抢购数量已用完，请等待正式抢购!');
        }
        // 提前时间
        $godTime = $god['godtime']['data'];
        // 取出场次
        $schedules = ApiRedis::updateGet(self::KEYS['RUSH_SCHEDULE'], function () {
            $sql_result = Db::name('rush_schedule')->field('*')
                ->order('starttime', 'asc');
            return $sql_result;
        });
        $findS = '';
        foreach ($schedules as $sv) {
            if ($sv['id'] == $sid) {
                $findS = $sv;
                break;
            }
        }
        // 没有找到场次信息
        if (empty($findS)) {
            $this->result_error("当前场次抢购失败!");
        }
        // 如果抢购场次已暂停
        if ($findS['state'] != 1) {
            $tip = $findS['tip'];
            if (!$tip) {
                $tip = '当前抢购已暂停抢购';
            }
            $this->result_error($tip);
        }
        $lastTime = time() + $godTime;
        $startArr = explode(':', $findS['starttime']);
        $endArr = explode(':', $findS['endtime']);
        $starttime = strtotime($y . '-' . $M . '-' . $d . ' ' . $startArr[0] . ':' . $startArr[1] . ':' . $startArr[2]);
        $endtime = strtotime($y . '-' . $M . '-' . $d . ' ' . $endArr[0] . ':' . $endArr[1] . ':' . $endArr[2]);
        if (!($lastTime >= $starttime && $lastTime < $endtime)) {
            $this->result_error('当前时间抢购失败!');
        }
        // 条件符合，进队列抢购
        $tempcount = APiRedisServer::selected(0)->HGET(self::KEYS['RUSH_GOODS_COUNTER'] . $sid,$gid);
        file_put_contents('./apirush.txt', '特权抢购前=>' . date('YmdHis', time()) . "当前场次{$sid}当前商品id={$gid}商品redis数量为{$tempcount}"."\r\n", FILE_APPEND);
        $lastCount = APiRedisServer::selected(0)->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, -1);
        file_put_contents('./apirush.txt', '特权时间=>' . date('YmdHis', time()) . "当前场次{$sid}当前商品id={$gid}商品redis数量为{$lastCount}"."\r\n", FILE_APPEND);
        if ((int)$lastCount == 0) {
//            $goods = Cache::store('redis')->HGET(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid);
            $goods = APiRedisServer::selected(0)->HGET(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid);
            if (!$goods) {
                $this->result_error('当前商品抢购失败!');
            }
            $goods = json_decode($goods, true);
            // 启动事务
            Db::startTrans();
            try {
                $order_id = ApiOrder::createRushOrder(
                    $user_info['id'],
                    $goods,
                    $sid,
                    $address_info
                );
                // 更新抢购商品状态
                $up_res = Db::name('goods_rush')->where('id', $gid)->update(['rusher_id' => $user_info['id'], 'state' => 2, 'next_time' => date('Y-m-d H:i:s', $endtime), 'current_order_id' => $order_id,]);// 上架时间设置成抢购场次结束后2小时
                if ($order_id > 0 && $up_res) {
                    Db::commit();
                } else {
                    $this->result_error('当前商品抢购失败!');
                }
                // 提交事务
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                APiRedisServer::selected(0)->hset(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
                $this->result_error('当前商品抢购失败!');
            }

            // 更新到抢购列表
            $data = Db::name('goods_rush')->where('id', $gid)->find();
//            Cache::store('redis')->hSet(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid, json_encode($data));
            APiRedisServer::selected(0)->hSet(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid, json_encode($data));
            try {
//                $ok_log = Cache::store('redis')->hGet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id']);
                $ok_log = APiRedisServer::selected(3)->hGet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id']);
                if ($ok_log) {
//                    Cache::store('redis')->hIncrBy(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id'], 1);
                    APiRedisServer::selected(3)->hIncrBy(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id'], 1);
                } else {
//                    Cache::store('redis')->hSet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id'], '1');
                    APiRedisServer::selected(3)->hSet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id'], '1');
                }
            } catch (\Exception $e) {
            }

            // 更新记录特权抢购数量
            if (
//                Cache::store('redis')->exists('special_success_' . $user_info['id'] . '_' . $sid . '_count')
            APiRedisServer::selected(2)->exists('special_success_' . $user_info['id'] . '_' . $sid . '_count')
            ) {
//                Cache::store('redis')->INCRBY('special_success_' . $user_info['id'] . '_' . $sid . '_count', 1);
                APiRedisServer::selected(2)->INCRBY('special_success_' . $user_info['id'] . '_' . $sid . '_count', 1);
            } else {
//                Cache::store('redis')->set('special_success_' . $user_info['id'] . '_' . $sid . '_count', 1, $timeout);
                APiRedisServer::selected(2)->setex('special_success_' . $user_info['id'] . '_' . $sid . '_count', $timeout, 1);
            }
            $this->result_ok("抢购成功，请尽快支付!");

        } elseif ($lastCount < 0) {
//            Cache::store('redis')->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
            // APiRedisServer::selected(0)->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
            $this->result_error("已抢完!");
        } else {
//            Cache::store('redis')->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
//             APiRedisServer::selected(0)->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
            $this->result_error("抢购失败!");
        }


    }
//    /** 获取用户成功抢购的数量 */
//    private function getUserRushSuccess($uid,$sid)
//    {
//        return Cache::store('redis')->get("success_{$uid}_{$sid}_count");
//    }
    /** 正常抢购  */
    public function shootNormal($user_info, $curTime, $y, $M, $d, $timeout, $gid, $sid, $address_info)
    {
        // 获取已经成功抢购的数量
        $success_count = ApiRedis::getUserRushSuccess($user_info['id'], $sid);
        $success_count = (int)($success_count);
        // 检查用户有没有秒杀数量限制，如果有是否已经满足
//        $common_count = Cache::store('redis')->get(self::KEYS['USER_COMMON_LIMIT']);
        $common_count = APiRedisServer::selected(2)->get(self::KEYS['USER_COMMON_LIMIT']);
        if (empty($common_count)) {
            $sql_result = Db::name('other_config')->where('id', 5)->find();
            $common_count = $sql_result['value1'];
//            Cache::store('redis')->set(self::KEYS['USER_COMMON_LIMIT'], $common_count);
            APiRedisServer::selected(2)->set(self::KEYS['USER_COMMON_LIMIT'], $common_count);
        } else {
            $common_count = (int)$common_count;
        }
        if ($common_count > 0) {
            if ($success_count >= $common_count) {
                $this->result_error("当日抢购数量已达上限!");
            }
        }

        // 取出场次
        $schedules = ApiRedis::updateGet(self::KEYS['RUSH_SCHEDULE'], function () {
            $sql_result = Db::name('rush_schedule')->field('*')
                ->order('starttime', 'asc');
            return $sql_result;
        });
        $findS = '';
        foreach ($schedules as $sv) {
            if ($sv['id'] == $sid) {
                $findS = $sv;
                break;
            }
        }
        // 没有找到场次信息
        if (empty($findS)) {
            $this->result_error("当前场次抢购失败!");
        }
        // 如果抢购场次已暂停
        if ($findS['state'] != 1) {
            $tip = $findS['tip'];
            if (!$tip) {
                $tip = '当前抢购已暂停抢购';
            }
            $this->result_error($tip);
        }
        $lastTime = time();
        $startArr = explode(':', $findS['starttime']);
        $endArr = explode(':', $findS['endtime']);
        $starttime = strtotime($y . '-' . $M . '-' . $d . ' ' . $startArr[0] . ':' . $startArr[1] . ':' . $startArr[2]);
        $endtime = strtotime($y . '-' . $M . '-' . $d . ' ' . $endArr[0] . ':' . $endArr[1] . ':' . $endArr[2]);
        if (!($lastTime >= $starttime && $lastTime < $endtime)) {
            $this->result_error('当前时间抢购失败!');
        }
        // 条件符合，进队列抢购
//        $lastCount = Cache::store('redis')->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, -1);
        $lastCount = APiRedisServer::selected(0)->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, -1);
        file_put_contents('./apirush.txt', '普通时间=>' . date('YmdHis', time()) . "当前场次{$sid}当前商品id={$gid}商品redis数量为{$lastCount}", FILE_APPEND);
        if ((int)$lastCount == 0) {
//            $goods = Cache::store('redis')->HGET(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid);
            $goods = APiRedisServer::selected(0)->HGET(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid);
            if (!$goods) {
                $this->result_error('抢购失败!');
            }
            $goods = json_decode($goods, true);
            // 启动事务
            Db::startTrans();
            try {
                $order_id = ApiOrder::createRushOrder(
                    $user_info['id'],
                    $goods,
                    $sid,
                    $address_info
                );
                // 更新抢购商品状态
                $up_res = Db::name('goods_rush')->where('id', $gid)->update(['rusher_id' => $user_info['id'], 'state' => 2, 'next_time' => date('Y-m-d H:i:s', $endtime), 'current_order_id' => $order_id,]);// 上架时间设置成抢购场次结束后2小时
                if ($order_id > 0 && $up_res) {
                    Db::commit();
                } else {
                    $this->result_error('当前商品抢购失败!');
                }
                // 提交事务
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                APiRedisServer::selected(0)->hset(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
                $this->result_error('当前商品抢购失败!');
            }
            // 更新到抢购列表
            $data = Db::name('goods_rush')->where('id', $gid)->find();
//            Cache::store('redis')->hSet(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid, json_encode($data));
            APiRedisServer::selected(0)->hSet(self::KEYS['RUSH_GOODS'] . $sid, (string)$gid, json_encode($data));

            ApiRedis::setUserRushSuccess($user_info['id'], $sid, $timeout, 1);

            try {
                $ok_log = APiRedisServer::selected(3)->hGet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id']);
//                $ok_log = Cache::store('redis')->hGet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id']);
                if ($ok_log) {
                    APiRedisServer::selected(3)->hIncrBy(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id'], 1);
                } else {
                    APiRedisServer::selected(3)->hSet(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $sid, $user_info['id'], '1');
                }
            } catch (\Exception $e) {
            }

            $this->result_ok("抢购成功，请尽快支付!");

        } elseif ($lastCount < 0) {
//            Cache::store('redis')->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
            $this->result_error("很遗憾,您没有抢到!", ['u' => $user_info['id'], 'c' => $lastCount, 'pc' => $lastCount]);
        } else {
//            Cache::store('redis')->HINCRBY(self::KEYS['RUSH_GOODS_COUNTER'] . $sid, $gid, 1);
            $this->result_error("很遗憾,您没有抢到!", ['u' => $user_info['id'], 'c' => $lastCount, 'pc' => $lastCount]);
        }

    }

    /**
     * 上架前支付
     * @param {*} req
     * @param {*} res
     * @returns
     */
    public function payPrepare()
    {
        $user_info = $this->user_info;
        $gid = Request::param('gid');
        $relate_order_id = Request::param('relate_order_id');
        $newprice = Request::param('newprice');
        $oldprice = Request::param('oldprice');
        $payprice = Request::param('payprice');
        $rate = Request::param('rate');
        $coupon_id = Request::param('coupon_id');
        if (!($gid > 0)) {
            $this->result_error('商品id错误!');
        }
        if (!($relate_order_id > 0)) {
            $relate_order_id = 0;
        }
        if (!($coupon_id > 0)) {
            $coupon_id = 0;
        }
        if (!($newprice > 0)) {
            $this->result_error('发布价格错误!');
        }
        if (!($oldprice > 0)) {
            $this->result_error('原价格错误!');
        }
        if (!($payprice > 0)) {
            $this->result_error('手续费价格错误!');
        }
        if (!($rate > 0)) {
            $this->result_error('费率错误!');
        }
        // 检查是否到可以上架时间
        $goodsRush = Db::name('goods_rush')->where('id', $gid)->find();
        $endTime = '';
        if (!empty($goodsRush) && !empty($goodsRush['next_time'])) {
            $endTime = $goodsRush['next_time'];
        }
        $sql_result = Db::name('other_config')->where('id', 6)->find();
        $launchTime = ($sql_result['value1'] ?? 2) * 3600;
        if ($endTime) {
            $endTimestamp = strtotime($endTime);
            if ((time() - $endTimestamp) < $launchTime) {
                $this->result_error('商品未到上架时间，还不允许上架');
            }
        }
        $order_info = ApiOrder::createPublishOrder($user_info['id'], $gid, $newprice, $oldprice, $payprice, $rate, $coupon_id, $relate_order_id);
        if (is_int($order_info)) {
            $this->result_error('获取支付信息失败', []);
        }
        // 订单显示名称
        $gname = '抢购商品:' . $goodsRush['name'] . $goodsRush['code'] . $goodsRush['id'];
        if (strlen($gname) > 127) {
            $gname = substr($gname, 0, 120) . '...';
        }
        $payprepare = ApiWxPay::getPay($gname, $order_info['order_no'], $payprice, $user_info['open_id'], $user_info['id'], $gid);
        if ($payprepare['status'] = 200) {
            $this->result_ok('ok', $payprepare);
        } else {
            $this->result_error('获取支付信息失败', $payprepare);
        }


    }

    public function aliPayPrepare()
    {
        $user_info = $this->user_info;
        $gid = Request::param('gid');
        $relate_order_id = Request::param('relate_order_id');
        $newprice = Request::param('newprice');
        $oldprice = Request::param('oldprice');
        $payprice = Request::param('payprice');
        $rate = Request::param('rate');
        $coupon_id = Request::param('coupon_id');
        if (!($gid > 0)) {
            $this->result_error('商品id错误!');
        }
        if (!($relate_order_id > 0)) {
            $relate_order_id = 0;
        }
        if (!($coupon_id > 0)) {
            $coupon_id = 0;
        }
        if (!($newprice > 0)) {
            $this->result_error('发布价格错误!');
        }
        if (!($oldprice > 0)) {
            $this->result_error('原价格错误!');
        }
        if (!($payprice > 0)) {
            $this->result_error('手续费价格错误!');
        }
        if (!($rate > 0)) {
            $this->result_error('费率错误!');
        }
        // 检查是否到可以上架时间
        $goodsRush = Db::name('goods_rush')->where('id', $gid)->find();
        $endTime = '';
        if (!empty($goodsRush) && !empty($goodsRush['next_time'])) {
            $endTime = $goodsRush['next_time'];
        }
        $sql_result = Db::name('other_config')->where('id', 6)->find();
        $launchTime = ($sql_result['value1'] ?? 2) * 3600;
        if ($endTime) {
            $endTimestamp = strtotime($endTime);
            if ((time() - $endTimestamp) < $launchTime) {
                $this->result_error('商品未到上架时间，还不允许上架');
            }
        }
        $order_info = ApiOrder::createPublishOrder($user_info['id'], $gid, $newprice, $oldprice, $payprice, $rate, $coupon_id, $relate_order_id);
        if (is_int($order_info)) {
            $this->result_error('获取支付信息失败', []);
        }
        // 订单显示名称
        $gname = '抢购商品:' . $goodsRush['name'] . $goodsRush['code'] . $goodsRush['id'];
        if (strlen($gname) > 127) {
            $gname = substr($gname, 0, 120) . '...';
        }
        $payprepare = ApiAliPay::getPay($gname, $order_info['order_no'], $payprice, $user_info['open_id'], $user_info['id'], $gid);
        if ($payprepare['status'] = 200) {
            $this->result_ok('ok', $payprepare);
        } else {
            $this->result_error('获取支付信息失败', $payprepare);
        }
    }

    /** 投诉订单【2】 */
    public function disputeOrder()
    {
        $gid = Request::param('gid');
        $dispute = Request::param('dispute');
        if (!($gid > 0)) {
            $this->result_error('商品id错误!');
        }
        if (empty($dispute) || !preg_replace('/\s*/', '', $dispute)) {
            $this->result_error("请详细描述投诉内容");
        }
        $sql_result = Db::name('goods_rush')->where('id', $gid)->whereIn('state', [2, 3])->find();
        if (empty($sql_result)) {
            $this->result_error("当前订单暂不能投诉");
        }
        Db::transaction(function () use ($gid, $dispute, $sql_result) {

        });
        // 启动事务
        Db::startTrans();
        try {
            $r1 = Db::name('user_order')->where('gid', $gid)->where('order_id', $sql_result['current_order_id'])->update(['dispute' => $dispute]);
            $r2 = Db::name('goods_rush')->where('id', $gid)
                ->whereIn('state', [2, 3])
                ->where('belong', $this->user_info['id'])
                ->update(['state' => 5]);
            if ($r1 && $r2) {
                // 提交事务
                Db::commit();
                $this->result_ok("已投诉，请耐心等待管理员解决");
            } else {
                // 回滚事务
                Db::rollback();
                $this->result_error("投诉失败");
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result_error("投诉失败");
        }


    }

    /**
     *设置支付截图（买家操作）
     */
    public function setPayPic()
    {
        $gid = Request::param('gid');
        if (!($gid > 0)) {
            $this->result_error('商品id错误!');
        }
        $up_res = Db::name('goods_rush')->where('rusher_id', $this->user_info['id'])->where('state', 2)->where('id', $gid)->update(['state' => 3]);
        if ($up_res) {
            $this->result_ok('ok');
        }
        $this->result_error("设置失败");

    }

    /** 支付确认(卖家操作) */
    public function payAck()
    {
        $gid = Request::param('gid');
        $order_id = Request::param('order_id');
        $order_no = Request::param('order_no');
        $price = Request::param('price');
        if (!($gid > 0)) {
            $this->result_error('商品id错误!');
        }
        if (!($order_id > 0)) {
            $this->result_error('订单id错误!');
        }
        if (empty($order_no)) {
            $this->result_error('订单号错误!');
        }
        if (!($price > 0)) {
            $this->result_error('订单价格错误!');
        }
        $findRusher = "SELECT a.*,b.belong,b.publish_order_no FROM sy_user a INNER JOIN sy_goods_rush b ON a.id=b.rusher_id WHERE b.id=? AND b.state=3 AND b.belong=?";
        $rusher_info = Db::query($findRusher, [$gid, $this->user_info['id']]);
        if (count($rusher_info) < 1) {
            $this->result_error('订单状态异常!');
        }
        $rusher_info = $rusher_info[0];
        // 启动事务
        Db::startTrans();
        try {
            $r1 = Db::name('user_order_publish')->where('order_no', $rusher_info['publish_order_no'])->where('uid', $rusher_info['belong'])->update(['hassale' => 1]);
            $sql_result = Db::execute("UPDATE sy_goods_rush SET state=0,last_belong=belong,belong=rusher_id,rusher_id=0 WHERE id=? AND state=3 AND belong=? AND current_order_id=?", [$gid, $this->user_info['id'], $order_id]);
            if ($sql_result) {
                // 更新订单
                $r2 = Db::execute("UPDATE sy_user_order SET pay_state=1 WHERE order_no=?", [$order_no]);
                // 更新推荐人收益
                if ($rusher_info['level1_recommender'] > 0) {
                    // 获取收益率
                    $rate = Db::name('other_config')->where('id', 2)->find();
                    if (!empty($rate)) {
                        $rate = $rate['value3'];
                    } else {
                        $rate = 3;
                    }
                    $income = (int)($price * $rate * 0.001);
                    $r1income = Db::name('user_income')->where('id', $rusher_info['level1_recommender'])->find();
                    $beforeTotal = 0;
                    $beforeAvaliable = 0;
                    if (!empty($r1income)) {
                        $beforeTotal = $r1income['income_total'];
                        $beforeAvaliable = $r1income['income'];
                        $r3 = Db::execute("UPDATE sy_user_income SET income_total=income_total+?,income=income+?,income_order_count=income_order_count+1 WHERE id=?", [$income, $income, $rusher_info['level1_recommender']]);
                    } else {
                        $r3 = Db::execute("INSERT INTO sy_user_income (id,income_total,income,income_order_count) VALUES (?,?,?,1)", [$rusher_info['level1_recommender'], $income, $income]);
                    }
                    $r4 = Db::execute("INSERT INTO sy_user_income_record (uid,order_id,order_no,fans_level,fans_uid,before_total_income,before_available_income,income,rate) 
            VALUES (?,?,?,?,?,?,?,?,?)", [$rusher_info['level1_recommender'], $order_id, $order_no, 1, $rusher_info['id'], $beforeTotal, $beforeAvaliable, $income, $rate]);
                }

                if ($rusher_info['level2_recommender'] > 0) {
                    // 获取收益率
                    $rate = Db::name('other_config')->where('id', 3)->find();
                    if (!empty($rate)) {
                        $rate = $rate['value3'];
                    } else {
                        $rate = 2;
                    }
                    $income = (int)($price * $rate * 0.001);
                    $r1income = Db::name('user_income')->where('id', $rusher_info['level2_recommender'])->find();
                    $beforeTotal = 0;
                    $beforeAvaliable = 0;
                    if (!empty($r1income)) {
                        $beforeTotal = $r1income['income_total'];
                        $beforeAvaliable = $r1income['income'];
                        $r3 = Db::execute("UPDATE sy_user_income SET income_total=income_total+?,income=income+?,income_order_count=income_order_count+1 WHERE id=?", [$income, $income, $rusher_info['level2_recommender']]);
                    } else {
                        $r3 = Db::execute("INSERT INTO sy_user_income (id,income_total,income,income_order_count) VALUES (?,?,?,1)", [$rusher_info['level2_recommender'], $income, $income]);
                    }
                    $r4 = Db::execute("INSERT INTO sy_user_income_record (uid,order_id,order_no,fans_level,fans_uid,before_total_income,before_available_income,income,rate) 
            VALUES (?,?,?,?,?,?,?,?,?)", [$rusher_info['level2_recommender'], $order_id, $order_no, 2, $rusher_info['id'], $beforeTotal, $beforeAvaliable, $income, $rate]);
                }
                Db::commit();
                $this->result_ok("ok");

            }
            Db::commit();
            $this->result_ok("ok");
//         提交事务

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result_error($e->getMessage());
        }
    }

    /** 生成抢购商品计数器 */
    public function createRushGoodsCounter()
    {

    }

    public function newUserPrivilege()
    {

    }

    public function useNewUserPrivilege()
    {

    }

}